package com.wetsion.securityoauthdemo.rmsclient.autoconfigure;

import com.wetsion.securityoauthdemo.rmsclient.common.RmsAccessTokenRequest;
import com.wetsion.securityoauthdemo.rmsclient.common.RmsClientDetailsProperties;
import com.wetsion.securityoauthdemo.rmsclient.common.RmsOauthClientContext;
import com.wetsion.securityoauthdemo.rmsclient.filter.RmsOauthFilter;
import com.wetsion.securityoauthdemo.rmsclient.handler.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2ClientContext;

import java.util.Map;

/**
 * @author weixin
 * @version 1.0
 * @CLassName RmsOauthAutoConfiguration
 * @date 2019/3/8 3:20 PM
 */
@Configuration
@ServletComponentScan("com.wetsion.securityoauthdemo.rmsclient")
@EnableConfigurationProperties({RmsClientDetailsProperties.class})
public class RmsOauthAutoConfiguration {

    @ConditionalOnBean(RmsOauthFilter.class)
    @Bean
    @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public RmsAccessTokenRequest rmsAccessTokenRequest(
            @Value("#{request.parameterMap}") Map<String, String[]> parameters,
            @Value("#{request.getAttribute('currentUri')}") String currentUri) {
        RmsAccessTokenRequest rmsAccessTokenRequest = new RmsAccessTokenRequest(parameters);
        rmsAccessTokenRequest.setCurrentUri(currentUri);
        return rmsAccessTokenRequest;
    }

    @ConditionalOnBean(RmsOauthFilter.class)
    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public RmsOauthClientContext rmsOauthClientContext(RmsAccessTokenRequest rmsAccessTokenRequest) {
        return new RmsOauthClientContext(rmsAccessTokenRequest);
    }
}
